﻿using Hangfire;
using Hangfire.Dashboard;
using Hangfire.MemoryStorage;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HangfireDemo.Hfs
{
    public class HangfireSetup
    {
        public static IServiceCollection HangfireServices(IServiceCollection services, IConfiguration configuration)
        {
            GlobalStateHandlers.Handlers.Add(new SucceededStateExpireHandler(int.Parse(configuration["Hangfire:JobExpirationTimeout"])));
            services.AddHostedService<RecurringJobsService>();
            services.AddHangfire(x =>
            {
                /* //使用Redis存储
                var connectionString = Configuration["Hangfire:Redis:ConnectionString"];
                x.UseRedisStorage(connectionString, new RedisStorageOptions()
                {
                    //活动服务器超时时间
                    InvisibilityTimeout = TimeSpan.FromMinutes(60),
                    Db = int.Parse(Configuration["Hangfire:Redis:Db"])
                });*/
                x.UseStorage(new MemoryStorage(
                    new MemoryStorageOptions
                    {
                        JobExpirationCheckInterval = TimeSpan.FromHours(1), //- 作业到期检查间隔（管理过期记录）。默认值为1小时。
                        CountersAggregateInterval = TimeSpan.FromMinutes(5), //- 聚合计数器的间隔。默认为5分钟。
                    }
                ));
                x.UseDashboardMetric(DashboardMetrics.ServerCount)
                        .UseDashboardMetric(DashboardMetrics.RecurringJobCount)
                        .UseDashboardMetric(DashboardMetrics.RetriesCount)
                        .UseDashboardMetric(DashboardMetrics.AwaitingCount)
                        .UseDashboardMetric(DashboardMetrics.EnqueuedAndQueueCount)
                        .UseDashboardMetric(DashboardMetrics.ScheduledCount)
                        .UseDashboardMetric(DashboardMetrics.ProcessingCount)
                        .UseDashboardMetric(DashboardMetrics.SucceededCount)
                        .UseDashboardMetric(DashboardMetrics.FailedCount)
                        .UseDashboardMetric(DashboardMetrics.EnqueuedCountOrNull)
                        .UseDashboardMetric(DashboardMetrics.FailedCountOrNull)
                        .UseDashboardMetric(DashboardMetrics.DeletedCount);
            });
            return services;
        }

        internal static void UseHangfireServer(IApplicationBuilder app, IConfiguration configuration)
        {
            app.UseHangfireDashboard(configuration["Hangfire:DashboardPath"], new DashboardOptions
            {
                Authorization = new[]
                {
                   new HangfireAuthorizationFilter()
                },
            });
            var jobOptions = new BackgroundJobServerOptions
            {
                Queues = new[] { "critical", "test", "default" },
                WorkerCount = Environment.ProcessorCount * int.Parse(configuration["Hangfire:ProcessorCount"]),
                ServerName = configuration["Hangfire:ServerName"],
                SchedulePollingInterval = TimeSpan.FromSeconds(30), //计划轮询间隔  支持任务到秒
            };
            app.UseHangfireServer(jobOptions);
        }
    }
}
